<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>用户注册</h2>
      </div>
      
      <el-form 
        ref="registerFormRef" 
        :model="registerForm" 
        :rules="registerRules" 
        class="register-form"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="userType">
          <el-radio-group v-model="registerForm.userType" class="user-type-radio">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item prop="name">
          <el-input 
            v-model="registerForm.name" 
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="请输入邮箱"
            prefix-icon="Message"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            class="register-button" 
            :loading="loading"
            @click="handleRegister"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="register-footer">
        <p>
          已有账号？
          <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'Register',
  setup() {
    const router = useRouter()
    const registerFormRef = ref()
    const loading = ref(false)
    
    const registerForm = reactive({
      userType: 'user', // 默认为普通用户
      name: '',
      email: '',
      password: '',
      confirmPassword: ''
    })
    
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    const registerRules = {
      userType: [
        { required: true, message: '请选择用户类型', trigger: 'change' }
      ],
      name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
      ],
      confirmPassword: [
        { validator: validateConfirmPassword, trigger: 'blur' }
      ]
    }
    
    const handleRegister = async () => {
      if (!registerFormRef.value) return
      
      await registerFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          
          try {
            // 调用后端注册API
            const response = await fetch('/api/auth/register', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                user_type: registerForm.userType,
                name: registerForm.name,
                email: registerForm.email,
                password: registerForm.password,
                password_confirmation: registerForm.confirmPassword
              })
            })
            
            // 检查响应状态
            if (!response.ok) {
              const errorText = await response.text()
              console.error('Server responded with status:', response.status, 'Response text:', errorText)
              throw new Error(`HTTP error! status: ${response.status}, response: ${errorText}`)
            }
            
            const result = await response.json()
            
            if (result.success) {
              // 根据用户类型显示不同成功消息
              if (registerForm.userType === 'admin') {
                ElMessage.success('管理员注册成功，请等待审核')
              } else {
                ElMessage.success('注册成功')
              }
              
              // 跳转到登录页面
              router.push('/login')
            } else {
              // 显示具体的错误信息
              ElMessage.error(result.message || '注册失败')
              if (result.errors) {
                console.error('Register validation errors:', result.errors)
                // 可以将错误信息展示给用户
                Object.keys(result.errors).forEach(key => {
                  ElMessage.error(result.errors[key][0])
                })
              }
            }
          } catch (error) {
            console.error('Register error:', error)
            if (error.name === 'TypeError' && error.message.includes('fetch')) {
              ElMessage.error('网络连接失败，请检查后端服务是否启动')
            } else if (error.message.includes('HTTP error')) {
              ElMessage.error('服务器返回错误，请查看控制台日志')
            } else {
              ElMessage.error('注册失败，请稍后重试')
            }
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    const goToLogin = () => {
      router.push('/login')
    }
    
    return {
      registerFormRef,
      registerForm,
      registerRules,
      loading,
      handleRegister,
      goToLogin
    }
  }
})
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px 30px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.register-form {
  margin-bottom: 20px;
}

.register-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  margin-top: 10px;
}

.register-footer {
  text-align: center;
  color: #666;
}

.register-footer p {
  margin: 0;
}

.user-type-radio {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>